package cn.usbtg.sutil;

import java.text.DecimalFormat;
import java.util.Random;
import java.util.UUID;

/**
 * 封装各种生成唯一性ID算法的工具类.
 */
public class Identities {

    /**
     * 获取一个指定区间[min,max]内的随机整数
     *
     * @param min
     * @param max
     * @return
     */
    public static String random(int min, int max) {
        return String.valueOf(new Random().nextInt(max - min + 1) + min);
    }

    /**
     * 获取一个指定长度的随机整数（支持0到9位长度）
     *
     * @param length
     * @return
     */
    public static String random(int length) {
        if (length <= 0) return "";
        length = length > 9 ? 9 : length;
        DecimalFormat format = new DecimalFormat("#");
        int min = Integer.valueOf(format.format(Math.pow(10, length - 1)));
        int max = Integer.valueOf(format.format(Math.pow(10, length))) - 1;
        return random(min, max);
    }

    /**
     * 获取一个原始的uuid（带中划线"-"）
     *
     * @return
     */
    public static String uuidOriginal() {
        return UUID.randomUUID().toString();
    }

    /**
     * 获取一个uuid
     *
     * @return
     */
    public static String uuid() {
        return uuidOriginal().replaceAll("-", "");
    }

    /**
     * 获取一个流水号（当前时间戳截取timestampBeginIndex到timestampEndIndex+randomLength位随机数）
     *
     * @param timestampBeginIndex
     * @param timestampEndIndex
     * @param randomLength
     * @return
     */
    public static String serialNo(int timestampBeginIndex, int timestampEndIndex, int randomLength) {
        String timestamp = DateUtil.getNowTimestamp();
        timestampEndIndex = timestampEndIndex <= 0 ? 0 : timestampEndIndex;
        timestampEndIndex = timestampEndIndex >= timestamp.length() - 1 ? timestamp.length() - 1 : timestampEndIndex;
        timestampBeginIndex = timestampBeginIndex <= 0 ? 0 : timestampBeginIndex;
        timestampBeginIndex = timestampBeginIndex >= timestamp.length() - 1 ? timestamp.length() - 1 : timestampBeginIndex;
        if (timestampBeginIndex > timestampEndIndex) {
            int temp = timestampBeginIndex;
            timestampBeginIndex = timestampEndIndex;
            timestampEndIndex = temp;
        }
        return DateUtil.getNowTimestamp().substring(timestampBeginIndex, timestampEndIndex) + random(randomLength);
    }

    /**
     * 获取一个流水号（当前时间年月日时分秒+6位随机数）
     *
     * @return
     */
    public static String serialNo() {
        return serialNo(0, 14, 6);
    }
}